<template>
  <div class="login">
    <el-form
      :model="formData"
      ref="ruleForm"
      class="login-form"
      size="small"
      :rules="rules">
      <div class="title">里由美术馆</div>
      <el-form-item prop="name">
        <el-input v-model="formData.account" placeholder="请输入账户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="formData.pwd" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">立即登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { login } from '@/api/account';

export default {
  data() {
    return {
      formData: {
        account: '',
        pwd: '',
      },
      rules: {
        account: [{ required: true, message: '用户名不能为空' }],
        pwd: [{ required: true, message: '密码不能为空' }],
      },
    };
  },
  methods: {
    login() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          try {
            const result = await login(this.formData);
            const { token, adminUser } = result;
            const { account, roleType } = adminUser;
            localStorage.setItem('account', account);
            localStorage.setItem('roleType', roleType);
            localStorage.setItem('token', token);
            const { from } = this.$route.query;
            setTimeout(() => {
              window.location.href = from ? decodeURIComponent(from) : '/';
            }, 500);
          } catch (err) {
            console.log(err);
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.login {
  .login-form {
    margin: 25vh auto;
    width: 250px;
    background: #fff;
    padding: 30px;
    padding-bottom: 20px;
    ::v-deep .el-button {
      margin-top: 5px;
      width: 100%;
    }
    .title {
      padding-bottom: 25px;
      font-size: 16px;
      font-weight: 600;
      text-align: center;
    }
  }
}
</style>
